﻿using System;
using Gfw.Infrastructure.ExceptionImpl;
using Gfw.Infrastructure.Facilities;
using Gfw.Infrastructure.Stock.Enums;
using Gfw.Models.Stock;
using Gfw.Repositories.Stock;
using Gfw.Repository;

namespace Gfw.Infrastructure.Stock.Facilities
{

    public class BuyTradeFacility : IFacility
    {
        private string _userId;
        private decimal _count;
        private decimal _price;
        ForceTradeTypeEnum _forceType = ForceTradeTypeEnum.Normal;

        public BuyTradeFacility(string userId, decimal count, decimal price)
        {
            _price = price;
            _count = count;
            _userId = userId;
        }
        public BuyTradeFacility(string userId, decimal count, decimal price, ForceTradeTypeEnum forceType)
        {
            _price = price;
            _count = count;
            _userId = userId;
            _forceType = forceType;
        }
        public virtual void Execute(Repository.UnitOfWork unitOfWork = null)
        {
            if (unitOfWork != null)
                throw new GfwTransactionInvalidException("该事务只能以原子状态执行。BuyTradeFacility");
            var work = unitOfWork ?? new UnitOfWork();
            UserAccountRepository accountRep = new UserAccountRepository();
            var account = accountRep.Get(_userId);
            if (account.IsLock != (int)AccountLockEnum.Normal)
            {
                throw new GfwException("用户帐户已经被锁定，不能进行交易。");
            }

            if (_count * _price > account.StockMoney)
            {
                throw new GfwTransactionInvalidException("帐户余额不足。");
            }

            var date = DateTime.Now;
            StkBargainagency agency = new StkBargainagency()
                                          {
                                              AgencyCount = _count,
                                              AgencyDate = date,
                                              AgencyPrice = _price,
                                              //Income = 0,
                                              //Taxation = 0,
                                              Userid = _userId,
                                              AccountType = (int)AccountTypeEnum.User,
                                              TradeType = (int) TradeTypeEnum.Buy,
                                              TradeStatus = (int) TradeStatusEnum.WaitTrade,
                                              ForceTradeType =(int) _forceType
                                          };
            TradeFacility tf = new TradeFacility(agency);
            tf.Execute(work);

            account.StockMoney -= _count * _price;
            accountRep.Update(account);

            work.Commit();

            //TradeManager.Execute();
            //StockManager.NotifyTrade();
        }
    }
}
